﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Net.Fan.SmallPig.BusinessRules;
using Net.Fan.SmallPig.DataAccess;
using Net.Fan.SmallPig.Common.DBMeta;
using System.Data;
using Net.Fan.SmallPig.Common;

public partial class Workflow_DefineWorkflow : System.Web.UI.Page
{
    enum Model
    {
        InsertWorflow, UpdateWorkflow, UpdateActivity
    }

    //Model model = Model.Update;
    long? workflowId;
    long? activityId;

    protected void Page_Load(object sender, EventArgs e)
    {
        
        PagePermission.CheckIsAdmin(this);
        //workfow ID
        string w = Request.Params["W"];
        //Activity ID
        string a = Request.Params["A"];
        if (w == null && a == null)
        {
            //Add a new workflow
            if (IsPostBack == false)
            {
                this.ViewState["model"] = Model.InsertWorflow;
                ButtonUpdateWorkflow.Text = "新增流程";
                PanelActivities.Visible = false;
                PanelInitState.Visible = false;
                PanelInUse.Visible = false;
            }
        }
        else
        {
            // update model

            if (a != null)
            {
                //update an activity
                this.ViewState["model"] = Model.UpdateActivity;
                long tmp;
                bool b = long.TryParse(a, out tmp);
                if (b)
                {
                    activityId = tmp;
                    workflowId = WorkflowDA.GetWorkflowIDbyActivity(activityId.Value);
                }
                else
                {
                    Response.Write("活动编号错误!");
                    Response.End();
                }
            }

            if (w != null)
            {
                //update a workflow
                this.ViewState["model"] = Model.UpdateWorkflow;
                long tmp;
                bool b = long.TryParse(w, out tmp);
                if (b)
                {
                    workflowId = tmp;
                }
                else
                {
                    Response.Write("工作流编号错误!");
                    Response.End();
                }
            }

            if (IsPostBack == false)
            {
                //Binding & fill controls data.
                DataRow dr = WorkflowDA.GetWorkflow(workflowId.Value);
                initControlsData(dr);
            }
        }

        //PagePermission.CheckPermission(this, Permission.Permissions.WorkflowDefine.ToString());
    }

    private void initControlsData(DataRow drWorkflow)
    {
        LabelWorkflowId.Text = drWorkflow[WorkflowMeta.WorkflowID].ToString();
        TextBoxWorkflowName.Text = drWorkflow[WorkflowMeta.WorkflowName].ToString();
        TextBoxDescription.Text = drWorkflow[WorkflowMeta.Description].ToString();

        bindingInUseControl(drWorkflow);

        ButtonUpdateWorkflow.Text = "保存流程";

        #region setup init end state

        var fstates = WorkflowDA.GetAllCurrentStates(workflowId.Value);
        foreach (var item in fstates)
        {
            DropDownListInitState.Items.Add(new ListItem(item));
        }
        var initState = drWorkflow[WorkflowMeta.InitState] as string;
        DropDownListInitState.SelectedValue = initState;

        var estates = WorkflowDA.GetAllNextStates(workflowId.Value);
        foreach (var item in estates)
        {
            DropDownListEndState.Items.Add(new ListItem(item));
        }
        var finizState = drWorkflow[WorkflowMeta.EndState] as string;
        DropDownListEndState.SelectedValue = finizState;

        #endregion //setup init end state

        //setup activities 
        initActiveControlsData();
    }

    private void initActiveControlsData()
    {
        DataTable dt = WorkflowBiz.GetActivities(workflowId.Value);
        if (dt.Rows.Count == 0)
        {
            LabelNoActivities.Visible = true;
        }
        else
        {
            LabelNoActivities.Visible = false;
            GridViewActivities.DataSource = dt;
            GridViewActivities.DataBind();
        }


        //check activities error
        string errorState = WorkflowBiz.CheckStateintegrality(workflowId.Value);
        labelActivities.Text = errorState;
        //if (errorState != null)
        //{
        //    labelActivities.Text = string.Format("流程还不完整，状态:‘{0}’不可到达。", errorState);
        //}

        if (activityId.HasValue)
        {
            LabelActivityStatus.Text = "您可以修改或删除此活动:";
            DataRow drActivity = WorkflowDA.GetActivity(activityId.Value);
            txtCurrentState.Text = drActivity[WorkflowMeta.CurrentState] as string;
            txtAction.Text = drActivity[WorkflowMeta.Operate] as string;
            txtNextState.Text = drActivity[WorkflowMeta.NextState] as string;
            textBoxOperators.Text = WorkflowBiz.GetOperators(activityId.Value);

        }
        else
        {
            LabelActivityStatus.Text = "您可以新增一个活动:";
            btUpdateActivity.Enabled = false;
            ButtonDeleteActivity.Enabled = false;
        }
    }

    private void bindingInUseControl(DataRow drWorkflow)
    {
        bool inUse = false;
        if (drWorkflow[WorkflowMeta.InUse] is DBNull)
        {
            inUse = false;
        }
        else
        {
            inUse = (bool)(drWorkflow[WorkflowMeta.InUse]);
        }

        if (inUse)
        {
            LabelInUse.Text = "当前流程处于'启用'状态。";
            ButtonInUse.Text = "停用";

        }
        else
        {
            LabelInUse.Text = "当前流程处于'停用'状态。";
            ButtonInUse.Text = "启用";
        }
    }


    protected void ButtonUpdateWorkflow_Click(object sender, EventArgs e)
    {
        ButtonUpdateWorkflow.Enabled = false;

        Model m = (Model)ViewState["model"];
        switch (m)
        {
            case Model.InsertWorflow:
                {
                    workflowId = WorkflowDA.InsertWorkflow(TextBoxWorkflowName.Text.Trim(), TextBoxDescription.Text, Page.User.Identity.Name);
                    break;
                }
            case Model.UpdateWorkflow:
            case Model.UpdateActivity:
                {
                    int i = WorkflowDA.UpdateWorkflow(workflowId.Value, TextBoxWorkflowName.Text.Trim(), TextBoxDescription.Text.Trim(), Page.User.Identity.Name);
                    break;
                }

            default:
                break;
        }

        Response.Redirect(string.Format("DefineWorkflow.aspx?W={0}", workflowId));
    }
    protected void ButtonNewActivity_Click(object sender, EventArgs e)
    {
        string currentState = this.txtCurrentState.Text.Trim();
        if (string.IsNullOrEmpty(currentState))
        {
            this.labMsg.Text = "当前状态不能为空。";
            return;
        }
        string action = this.txtAction.Text.Trim();
        if (string.IsNullOrEmpty(action))
        {
            this.labMsg.Text = "动作不能为空。";
            return;
        }

        string nextState = this.txtNextState.Text.Trim();
        if (string.IsNullOrEmpty(nextState))
        {
            this.labMsg.Text = "下一状态不能为空。";
            return;
        }

        Result r = WorkflowBiz.AddActivity(workflowId.Value, currentState, action, nextState, textBoxOperators.Text);
        if (r.ResultType == ResultType.OK)
        {
            this.labMsg.Text = "插入活动成功！";
            Response.Redirect(string.Format(Request.RawUrl));
        }
        else
        {
            this.labMsg.Text = r.Message;
        }



    }

    protected void btEdit_Click(object sender, EventArgs e)
    {
        string currentState = this.txtCurrentState.Text.Trim();
        if (string.IsNullOrEmpty(currentState))
        {
            this.labMsg.Text = "当前状态不能为空。";
            return;
        }
        string action = this.txtAction.Text.Trim();
        if (string.IsNullOrEmpty(action))
        {
            this.labMsg.Text = "动作不能为空。";
            return;
        }

        string nextState = this.txtNextState.Text.Trim();
        if (string.IsNullOrEmpty(nextState))
        {
            this.labMsg.Text = "下一状态不能为空。";
            return;
        }
        //int sid = int.Parse(this.GridViewActivities.SelectedRow.Cells[0].Text);
        Result r = WorkflowBiz.UpdateActivity(activityId.Value, currentState, action, nextState, textBoxOperators.Text);
        if (r.ResultType == ResultType.OK)
        {
            this.labMsg.Text = "修改活动成功！";
            Response.Redirect(string.Format(Request.RawUrl));
        }
        else
        {
            this.labMsg.Text = r.Message;
        }
    }

    protected void txtAction_TextChanged(object sender, EventArgs e)
    {

    }
    protected void ButtonDeleteActivity_Click(object sender, EventArgs e)
    {
        WorkflowBiz.DelActivity(activityId.Value);
        Response.Redirect(string.Format("{0}?W={1}", Request.Path, workflowId));
    }
    protected void DropDownListInitState_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownListInitState.SelectedIndex == 0)
        {

        }
        else
        {
            WorkflowDA.UpdateInitState(workflowId.Value, DropDownListInitState.SelectedValue);
            Response.Redirect(Request.RawUrl);
        }
    }
    protected void ButtonInUse_Click(object sender, EventArgs e)
    {
        WorkflowBiz.TurnInUse(workflowId.Value);
        Response.Redirect(Request.RawUrl);
    }
    protected void DropDownListEndState_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownListInitState.SelectedIndex == 0)
        {

        }
        else
        {
            WorkflowDA.UpdateEndState(workflowId.Value, DropDownListEndState.SelectedValue);
            Response.Redirect(Request.RawUrl);
        }
    }
}
